<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\order;


use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\logic\auth\AdminLogic;
use app\common\enum\MediaSourceEnum;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole;
use app\common\model\auth\AdminTeam;
use app\common\model\auth\SystemRole;
use app\common\model\book\Bookread;
use app\common\model\click\UserCallbackLog;
use app\common\model\order\Order;
use app\common\lists\ListsSearchInterface;
use app\common\model\promotion\PromotionLink;
use app\common\model\user\User;
use app\common\service\BuyService;


/**
 * Order列表
 * Class OrderLists
 * @package app\adminapi\lists
 */
class OrderLists extends BaseAdminDataLists implements ListsSearchInterface
{


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/02/01 10:45
     */
    public function setSearch(): array
    {
        return [];
    }


    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/02/01 10:45
     */
    public function lists(): array
    {
        $params = $this->request->get();

        // TODO 管理员权限控制
        $pAdminIds = [];
        if ($this->adminInfo['root'] != 1) {
            $pAdminIds = AdminLogic::getPermissionAdminIds($this->adminInfo);
        }

        $bookId        = $params['book_id'] ?? '';
        $userId        = $params['user_id'] ?? '';
        $adId          = $params['ad_id'] ?? '';
        $advertisingId = $params['advertising_id'] ?? '';
        $promotionId   = $params['promotion_id'] ?? '';
        $transactionId = $params['transaction_id'] ?? '';
        $money         = $params['money'] ?? '';
        $adminId       = $params['admin_id'] ?? '';
        $payType       = $params['pay_type'] ?? '';
        $status        = $params['status'] ?? '';
        $isNew         = $params['is_new'] ?? '';
        $isFirst       = $params['is_first'] ?? '';
        $source        = $params['source'] ?? '';


        $query = Order::alias('order')->with([
            'quickapp' => function ($q) {
                $q->withField('id,name');
            },
            'user'     => function ($q) {
                $q->withField('id,register_time,is_new_user,egold,promotion_link_id');
            },
//            'callback' => function ($q) {
//                $q->withoutField('update_time,create_time');
//
//                $q->with([
//                    'link' => function ($q) {
//                        $q->withField('id,name,book_name,chapter_name');
//                    },
//                ]);
//                $q->with([
//                    'admin' => function ($q) {
//                        $q->withField('id,account');
//                    },
//                ]);
//            },

        ])->leftJoin('order_callback oc', 'order.id = oc.order_id');

//        $query->hasWhere('callback', function ($query) use (
//            $pAdminIds, $adId, $promotionId, $isNew, $isFirst, $adminId
//        ) {
//            if ($pAdminIds) {
//                $query->where('admin_id', 'in', $pAdminIds);
//            }
//            if ($adId) {
//                $query->where('ad_id', (int)$adId);
//            }
//            if ($promotionId) {
//                $query->where('promotion_link_id', $promotionId);
//            }
//            if ($isNew !== '') {
//                $query->where('is_new_user', $isNew);
//            }
//            if ($isFirst !== '') {
//                if ($isFirst == 1) {
//                    $query->where('recharge_times', 1);
//                } else {
//                    $query->where('recharge_times', '<>', 1);
//                }
//            }
//            if ($adminId) {
//                $query->where('admin_id', $adminId);
//            }
//        });

        if ($bookId) {
            $query->where('book_id', (int)$bookId);
        }

        if ($transactionId) {
            $query->where('transaction_id', $transactionId);
        }

        if ($money) {
            $query->where('money', $money);
        }

        if ($payType !== '') {
            $query->where('paytype', $payType);
        }

        if ($status !== '') {
            $query->where('status', $status);
        }

        if ($source !== '') {
            $query->where('source', $source);
        }

        if ($pAdminIds) {
            $query->where('order.admin_id', 'in', $pAdminIds);
        }
        if ($adId) {
            $query->where('oc.ad_id', (int)$adId);
        }
        if ($advertisingId) {
            $query->where('oc.advertising_id', (int)$advertisingId);
        }
        if ($promotionId) {
            $userIdArr = User::where('promotion_link_id',$promotionId)->column('id');
            $query->where('order.user_id', 'in',$userIdArr);
        }
        if ($userId) {
            $query->where('order.user_id', (int)$userId);
        }
        if ($isNew !== '') {
            $query->where('oc.is_new_user', $isNew);
        }
        if ($isFirst !== '') {
            if ($isFirst == 1) {
                $query->where('oc.recharge_times', 1);
            } else {
                $query->where('oc.recharge_times', '<>', 1);
            }
        }
        if ($adminId) {
            $query->where('order.admin_id', $adminId);
        }
        $list = $query->where($this->searchWhere)
            ->field('order.*,oc.order_id,oc.admin_id,oc.is_new_user,oc.recharge_times,oc.return_status,oc.return_rule_id,oc.match_status,oc.media_account_id,oc.promotion_link_id,oc.project_id,oc.project_name,oc.ad_id,oc.advertising_id,oc.ad_name,oc.dyeing_time,oc.reporting_time,oc.register_time')
            ->where($this->queryWhere())
            ->limit($this->limitOffset, $this->limitLength)
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
        foreach ($list as &$item){
            $item['source'] = MediaSourceEnum::getSourceDesc($item['source']);
            $item['advertising_id'] = ($item['advertising_id'] == 0) ? '' : $item['advertising_id'];
            if (!empty($item['promotion_link_id'])){
                $promotionLink = PromotionLink::where('id',$item['promotion_link_id'])->findOrEmpty();
                $item['promotion_name'] = $promotionLink->name??'';
                $item['book_name'] = $promotionLink->book_name??'';
                $item['chapter_name'] = $promotionLink->chapter_name??'';
                if (!empty($item['admin_id'])){
                    $admin = Admin::where('id',$item['admin_id'])->findOrEmpty();
                    $item['account'] = $admin->account??'';
                }
                if (!empty($item['dyeing_time'])){
                    $item['dyeing_time'] = date('Y-m-d H:i:s',$item['dyeing_time']);
                }else{
                    $item['dyeing_time'] = '-';
                }
                if (!empty($item['reporting_time'])){
                    $item['reporting_time'] = date('Y-m-d H:i:s',$item['reporting_time']);
                }else{
                    $item['reporting_time'] = '-';
                }
            }else{
                $item['promotion_link_id'] = $item['user']['promotion_link_id']??'';
            }
//            $order_date = date('Y-m-d',strtotime($item['create_time']));
//            $order_start_time = strtotime($order_date);
//            $order_end_time = strtotime($order_date)+86400;
//            $isUserCallbackLog = UserCallbackLog::where('user_id',$item['user_id'])->where('dyeing_time','between',[$order_start_time,$order_end_time])->findOrEmpty();
//            if (!$isUserCallbackLog->isEmpty()){
//                $item['is_new_user'] = 0;
//            }else{
//                $item['is_new_user'] = 1;
//            }
            if (isset($item['user'])){
                $item['zb'] = BuyService::getUserZb($item['user_id']);
                $item['user']['egold'] = $item['user']['egold']+$item['zb'];
                    $lastReadTime = Bookread::BookreadQuery($item['user_id'])
                        ->where('user_id', $item['user_id'])
                        ->order('create_time', 'desc')
                        ->value('create_time')??'';
                    if (!empty($lastReadTime)){
                        $lastReadTime = date('Y-m-d H:i:s',$lastReadTime);
                    }
                $item['user']['last_read_time'] = $lastReadTime;

                //判断订单生成当日是否有染色记录。有就是新用户
//                if (!$isUserCallbackLog->isEmpty()){
//                    $item['user']['is_new_user'] = 0;
//                }else{
//                    $item['user']['is_new_user'] = 1;
//                }
            }
        }
        return $list;
    }

    /**
     * @notes 搜索条件
     * @author 段誉
     * @date 2023/2/24 16:08
     */
    public function queryWhere()
    {
        $platform = $this->params['platform'] ?? '';
        $where    = [];
        // 下单时间
        if (!empty($this->params['start_time']) && !empty($this->params['end_time'])) {
            $time    = [strtotime($this->params['start_time']), strtotime($this->params['end_time'])];
            $where[] = ['order.create_time', 'between', $time];
        }
        if ($platform !== '') {
            $where[] = ['order.platform', '=', $platform];
        }

        return $where;
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/02/01 10:45
     */
    public function count(): int
    {
        $params = $this->request->get();
        // TODO 管理员权限控制
        $pAdminIds = [];
        if ($this->adminInfo['root'] != 1) {
            $pAdminIds = AdminLogic::getPermissionAdminIds($this->adminInfo);
        }

        $bookId        = $params['book_id'] ?? '';
        $userId        = $params['user_id'] ?? '';
        $adId          = $params['ad_id'] ?? '';
        $advertisingId = $params['advertising_id'] ?? '';
        $promotionId   = $params['promotion_id'] ?? '';
        $transactionId = $params['transaction_id'] ?? '';
        $money         = $params['money'] ?? '';
        $adminId       = $params['admin_id'] ?? '';
        $payType       = $params['pay_type'] ?? '';
        $status        = $params['status'] ?? '';
        $isNew         = $params['is_new'] ?? '';
        $isFirst       = $params['is_first'] ?? '';
        $source        = $params['source'] ?? '';


        $query = Order::alias('order')->with([
            'quickapp' => function ($q) {
                $q->withField('id,name');
            },
            'user'     => function ($q) {
                $q->withField('id,register_time,is_new_user,egold');
            },
//            'callback' => function ($q) {
//                $q->withoutField('update_time,create_time');
//                $q->with([
//                    'link' => function ($q) {
//                        $q->withField('id,name,book_name,chapter_name');
//                    },
//                ]);
//                $q->with([
//                    'admin' => function ($q) {
//                        $q->withField('id,account');
//                    },
//                ]);
//            },

        ])->leftJoin('order_callback oc', 'order.id = oc.order_id');

//        $query->hasWhere('callback', function ($query) use (
//            $pAdminIds, $adId, $promotionId, $isNew, $isFirst, $adminId
//        ) {
//            if ($pAdminIds) {
//                $query->where('admin_id', 'in', $pAdminIds);
//            }
//            if ($adId) {
//                $query->where('ad_id', (int)$adId);
//            }
//            if ($promotionId) {
//                $query->where('promotion_link_id', $promotionId);
//            }
//            if ($isNew !== '') {
//                $query->where('is_new_user', $isNew);
//            }
//            if ($isFirst !== '') {
//                if ($isFirst == 1) {
//                    $query->where('recharge_times', 1);
//                } else {
//                    $query->where('recharge_times', '<>', 1);
//                }
//            }
//            if ($adminId) {
//                $query->where('admin_id', $adminId);
//            }
//        });

        if ($bookId) {
            $query->where('book_id', (int)$bookId);
        }


        if ($transactionId) {
            $query->where('transaction_id', $transactionId);
        }

        if ($money) {
            $query->where('money', $money);
        }

        if ($payType !== '') {
            $query->where('paytype', $payType);
        }

        if ($status !== '') {
            $query->where('status', $status);
        }

        if ($source !== '') {
            $query->where('source', $source);
        }

        if ($pAdminIds) {
            $query->where('order.admin_id', 'in', $pAdminIds);
        }
        if ($adId) {
            $query->where('oc.ad_id', (int)$adId);
        }
        if ($advertisingId) {
            $query->where('oc.advertising_id', (int)$advertisingId);
        }
        if ($promotionId) {
            $userIdArr = User::where('promotion_link_id',$promotionId)->column('id');
            $query->where('order.user_id', 'in',$userIdArr);
        }
        if ($userId) {
            $query->where('order.user_id', (int)$userId);
        }
        if ($isNew !== '') {
            $query->where('oc.is_new_user', $isNew);
        }
        if ($isFirst !== '') {
            if ($isFirst == 1) {
                $query->where('oc.recharge_times', 1);
            } else {
                $query->where('oc.recharge_times', '<>', 1);
            }
        }
        if ($adminId) {
            $query->where('order.admin_id', $adminId);
        }

        return $query->where($this->searchWhere)->where($this->queryWhere())->select()->count();
    }

}
